package svc

import (
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/zrpc"
	"microdemo/restful/bff/internal/config"
	"microdemo/restful/bff/internal/middlewares"
	"microdemo/service/order/orderclient"
	"microdemo/service/stock/stockclient"
	"microdemo/service/user/userclient"
)

type ServiceContext struct {
	Config config.Config
	// 内部调用的 client 信息
	UserRpc  userclient.User
	OrderRpc orderclient.Order
	StockRpc stockclient.Stock
	// 自定义的中间件 UserAgentMiddleware
	UserAgentMiddleware rest.Middleware
	GlobalMiddleware rest.Middleware
}

func NewServiceContext(c config.Config) *ServiceContext {
	return &ServiceContext{
		Config:   c,
		// etcd 服务发现。内置了负载均衡策略 p2c_ewma。对应位置：github.com\zeromicro\go-zero@v1.6.0\zrpc\internal\client.go
		UserRpc:  userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),
		OrderRpc: orderclient.NewOrder(zrpc.MustNewClient(c.OrderRpc)),
		StockRpc: stockclient.NewStock(zrpc.MustNewClient(c.StockRpc)),
		// 注入 UserAgentMiddleware
		UserAgentMiddleware: middlewares.NewUserAgentMiddleware().Handle,
		GlobalMiddleware: middlewares.NewGlobalMiddleware().Handle,
	}
}
